<template>
  <div class="provider-info-record">
    <div class="provider-timeline" :style="inputState?'padding-bottom:170px;':'padding-bottom:70px;'" ref="timeline">
      <base-timeline
        :data="recordPage.list"
        :record-render="renderRecord"
        :loading="recordLoading"
        :loadmore="recordPage.hasNextPage"
        @load="loadmore"/>
    </div>

    <div class="customer-quick-comment" v-if="remarkEnable" :style="commentStyle">
      <biz-comment ref="comment" :placeholder="$t('common.base.tip.inputCommentContent')" @inputStateChange='inputStateChange' :submit-text="$t('common.base.submit')" @submit="createRemark" :disabled="commentPending" autofocus user-search-url="/message/user/lists" :search-params="{seeAllOrg:true}"></biz-comment>
    </div>

    <!-- start 人员卡片 -->
    <biz-user-card ref="userCard"></biz-user-card>
    <!-- end 人员卡片 -->
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import Page from '@model/Page';
import platform from '@src/platform';
import { getRootWindowInitData } from '@src/util/window'
/* api */
import * as ServiceProviderApi from '@src/api/serviceProviderApi';
import i18n from '@src/locales';
import { cutAtTextContent } from 'pub-bbx-utils'

function createAttachmentDom(h, attachments){
  return attachments && attachments.length > 0
    ? <div class="base-timeline-attachment base-file__preview">
      {attachments.map(item => <base-file-item Source={attachments} file={item} key={item.id} readonly size="small"/>)}
    </div>
    : ''
}
function createLinkDom(h, s){
  const reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;
  const str = s.replace(reg, str=>`@@${str}@@`);
  const arr = str.split('@@');
  return <p class="pre-line secondary-info">{arr.map(item=>{
    if(item.indexOf('http') === 0){
      return <a href={item} target='_blank'>{item}</a>
    }
    return <biz-comment-html html={item}></biz-comment-html>

  })}</p>
}
export default {
  name: 'engineer-info-record',
  props: {
    primaryId: {
      type: String,
      default: ''
    },
    tenantProviderId: {
      type: String,
      default: ''
    },
    providerName: {
      type: String,
      default: ''
    },
    remarkEnable: {
      type: Boolean,
      default: false, // 添加备注权限(工程师正常的并且有编辑工程师的权限)
    },
    collapseDirection: {
      type: String,
      default: '',
    },
  },
  computed: {
    commentStyle(){
      if(this.collapseDirection == 'left'){
        return 'width:calc(100% - 205px);bottom:0px;'
      }else if(this.collapseDirection === ''){
        return 'width:calc(50% - 50px);bottom:0px;'
      }return 'width:calc(70% - 25px);max-width:calc(100% - 445px);bottom:0px;'
    },
    loginUser() {
      return getRootWindowInitData().user
    },
  },
  data() {
    return {
      isOpenData,
      inputState:false,
      recordPage: new Page(),
      params: {
        primaryId: '',
        pageNum: 1,
        pageSize: 15,
        type: 2,
      },
      recordLoading: false,
      commentPending: false,
      actionEnum: {
        create: this.$t('common.base.create3'),
        update: this.$t('common.base.edit1'),
        stop: this.$t('common.base.logout'),
        log: this.$t('common.base.remark'),
        batchUpdate: this.$t('common.base.batchModify'),
        batchStop: this.$t('common.base.batchLogout'),
      }
    }
  },
  methods: {
    inputStateChange(val){
      this.inputState = val;
    },
    /** 添加备注 */
    async createRemark(form){
      try{
        this.commentPending = true;
        let url = ''
        if(form.receivers){
          url = `?tenantId=${this.loginUser?.tenantId}&&bizId=${this.primaryId}&&tenantProviderId=${this.tenantProviderId}&&sendUserName=${this.loginUser?.displayName}&&receivers=${form.receivers}&&templateId=''&&templateName=''&&bizNo=${this.providerName}`
          url += `&content=${cutAtTextContent(form.originalContent)}`
        }
        let params = {
          objectId: this.primaryId,
          content: form.content,
          showInOn: form.showInOwn,
          attachment: form.attachments,
        }
        let result = await this.$http.post(`/api/app/outside/provider/common/record/engineer/create${url}`, params);

        if(result.success){
          this.$refs.comment.reset();
          await this.initializeRecord();
          this.$nextTick(() => {
            this.$refs.timeline.scrollTop = 0;
          })
        }else{
          platform.alert(result.message)
        }

        this.commentPending = false;
      }catch(e){
        console.error(e)
      }
    },
    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, item){
      let {action, userName, showInOn, content, attachmentList, primaryName, staffId} = item;
      //
      if(action === 'log'){
        try {
          content = JSON.parse(content);
          return [
            <h5 class="main-info">
            <i18n path="serviceProvider.addRemark">
              <span place="user">{this.renderUserName(userName, staffId)}</span>
            </i18n>
              {!!showInOn && (
                <span class="private">
                  <i class="iconfont icon-account1"></i>
                  {this.$t('common.option.commentAction[0]')}
                </span>
              )}。
              {
                this.allowDeleteRecord(content)
                  && <el-button class="btn-text base-timeline-delete" onClick={e => this.deleteRemark(item)}>
                    <i class="iconfont icon-shanchu"></i>
                    {this.$t('common.base.delete')}
                  </el-button>
              }
            </h5>,
            content.isDelete == 'true'
              ? <p class="text-danger">
              {
                <i18n path="common.record.sbDeleteRemark">
                  <span place="name">{this.renderUserName(content.deleteUserName, content.deleteUserStaffId)}</span>
                  <span place="time">{content.deleteTime}</span>
                </i18n>
              }
              </p>
              : [createLinkDom(h, content.updateContent), createAttachmentDom(h, attachmentList)]
          ]
        } catch (e) {
          console.error(e)
        }
      }
      if(action === 'batchUpdate') {
        content = JSON.parse(content);
        return [
          <h5>{this.renderUserName(userName, staffId)} {this.actionEnum[action]} {this.$t('common.base.engineer')}。</h5>,
          content.displayName ? <p class="secondary-info">{this.$t('common.base.modifyField')}：{content.displayName}</p> : ''
        ];
      }
      if(action === 'update') {
        content = JSON.parse(content);
        let str = content.join(',')
        return [
          <h5>{this.renderUserName(userName, staffId)} {this.actionEnum[action]} {this.$t('common.base.engineer')}。</h5>,
          str ? <p class="secondary-info">{this.$t('common.base.modifyField')}：{str}</p> : ''
        ];
      }
      return [
        <h5>{this.renderUserName(userName, staffId)} {this.actionEnum[action]} {this.$t('common.base.engineer')}。</h5>,
        content.updateFields ? <p class="secondary-info">{this.$t('common.base.modifyField')}：{content.updateFields}</p> : '',
        createAttachmentDom(h, attachmentList)
      ];
    },
    /**
     * 同时满足以下条件允许删除该记录
     * 1. 该记录没有被删除
     * 2. 服务商编辑权限（CUSTOMER_EDIT）值为3
     * 3. 该服务商没有被删除
     */
    allowDeleteRecord(item){
      let isDelete = item?.isDelete == 'true';
      return !isDelete && this.remarkEnable;
    },
    /** 初始化信息动态 */
    async initializeRecord() {
      this.params.pageNum = 1;
      await this.searchRecord();
    },
    /** 加载下一页 */
    async loadmore() {
      try {
        this.params.pageNum++;
        this.recordLoading = true;
        let res = await this.fetchRecord(this.params);
        if(res.success) {
          this.recordLoading = false;
          this.recordPage.merge(res.result)
        }
      } catch (error) {
        console.error(error)
      }
    },
    /** 抓取信息动态 */
    fetchRecord(params){
      return ServiceProviderApi.getRecordList(params);
    },
    /** 删除备注 */
    async deleteRemark(record) {
      try {
        if (!await this.$platform.confirm(this.$t('common.base.tip.deleteRemarkTip'))) return;
        const delRes = await this.$http.post('/api/app/outside/provider/common/record/delete', {id: record.id, type: 2});
        if(delRes.success) {
          await this.initializeRecord();
        } else {
          this.$platform.alert(delRes.message)
        }
      } catch (e) {
        console.error('deleteMark catch err', e);
      }
    },
    async searchRecord() {
      try {
        this.recordLoading = true;
        let res = await this.fetchRecord(this.params);
        if(res.success) {
          this.recordLoading = false;
          this.recordPage.list = [];
          this.recordPage.merge(res.result)
        }
      } catch (error) {
        console.error(error)
      }
    },
    handleUserCard(event){
      this.$refs.userCard.open(event)
    },
    renderUserName(userName, staffId){
      if(isOpenData && staffId) return <strong>{<open-data type="userName" openid={staffId}></open-data>}</strong>
      return <strong>{userName}</strong>
    },
  },
  mounted() {
    this.params.primaryId = this.primaryId;
    this.initializeRecord();
    this.$eventBus.$on('comment-user-card', this.handleUserCard)
  },
  beforeDestroy() {
    this.$eventBus.$off('comment-user-card', this.handleUserCard)
  }
}
</script>

<style lang="scss">
.provider-info-record {
  height: 100%;
  display: flex;
  flex-flow: column nowrap;

  h5 {
    margin-bottom: 5px;
    .icon-address {
      margin-left: 5px;
    }
  }

  .private {
    @include fontColor();
    .iconfont {
      font-size: 14px;
      margin: 0 6px;
    }
  }

  .secondary-info {
    margin-top: 8px;
  }

  .error-info {
    color: #E51C23;
  }

}
.provider-timeline{
  padding-top: 15px;
  flex: 1;
  padding-right: 15px;
}

p.principal-info {
  margin-left: 70px;
}
</style>